#include "ConfigFile.h"
#include <algorithm> // for std::trim()
#include <functional> // for std::isspace()

ConfigFile::ConfigFile(const std::string& filename) : m_filename(filename){
	load();
}

ConfigFile::~ConfigFile() {

}

void ConfigFile::load()
{
	std::ifstream input(m_filename.c_str());

	if (!input)
	{
		std::cerr << "Failed to open input file: " << m_filename << "\n";
		return;
	}

	std::string line;
	while (std::getline(input, line))
	{
		// 忽略以 '#' 开头的注释行和空白行
		if (!line.empty() && line[0] != '#')
		{
			std::size_t pos = line.find("=");
			if (pos != std::string::npos)
			{
				std::string key = line.substr(0, pos);
				std::string value = line.substr(pos + 1);
				// 去掉key和value两边的空格
				key.erase(key.begin(), std::find_if(key.begin(), key.end(), [](int c) { return !std::isspace(c); }));
				key.erase(std::find_if(key.rbegin(), key.rend(), [](int c) { return !std::isspace(c); }).base(), key.end());

				value.erase(value.begin(), std::find_if(value.begin(), value.end(), [](int c) { return !std::isspace(c); }));
				value.erase(std::find_if(value.rbegin(), value.rend(), [](int c) { return !std::isspace(c); }).base(), value.end());
				m_params[key] = value;
			}
		}
	}

	input.close();
}

void ConfigFile::save()
{
	std::ofstream output(m_filename.c_str());

	if (!output)
	{
		std::cerr << "Failed to open output file: " << m_filename << "\n";
		return;
	}

	for (auto& param : m_params)
	{
		output << param.first << "=" << param.second << "\n";
	}

	output.close();
}

bool ConfigFile::get(const std::string& key, std::string& value)
{
	auto it = m_params.find(key);

	if (it != m_params.end())
	{
		value = it->second;
		return true;
	}

	return false;
}

void ConfigFile::set(const std::string& key, const std::string& value)
{
	m_params[key] = value;
}